#include "tasks.h"
#include "devices.h"
#include <devices_ext/mti.h>
#include <string.h>
#include <stdlib.h>

static const uint8_t mport = 1;
static const uint8_t uport = 0;
DEF_MTI_MSG( send, 8 );
DEF_MTI_MSG( errm, 8 );
/* 定义MTI消息空间 */
DEF_MTI_MSG( recv, 4*8 + 12 );
static Timer tmr;
char output[50];

DEF_TASK( mti, 300, 0 )
{
	MTIM_INIT( recv );
	uart_open( mport, UModeRW );

	MTIM_INIT( send );
	MTIM_INIT( errm );
	mtim_set_id( send, MTI_SINGLE );
	mtim_make( send, MtiMidGoToConfig, 0 );
	mtim_make( errm, MtiMidError, 0 );
	uart_open( uport, UModeRW );
#if WANT_CONFIG
	sleep_ms( &tmr, 1000 );
	mti_send( mport, send );
	if( mti_recv( mport, recv) == MtiMidGoToConfigAck ){
		uart_write( uport, "MtiConfigMode!\n", 15 );
		while( true ){
			int rid = mti_recv( uport, recv );
			if( rid >= 0 ){
				mti_send( mport, recv );
				if( rid == MtiMidGoToMeasurement ){
					uart_write( uport, "MtiMeasureMode!\n", 16 );
					break;
				}
				mti_recv( mport, recv );
				mti_send( uport, recv );
			} else {
				uart_write( uport, "MtiError!\n", 10 );
			}
		}
	}
#endif

	while( true ){
		if( mti_recv( mport, recv ) == MtiMidMTData ){
			itoa( mtim_get_int( recv, 0 ), output, 10 );
			strcat( output, ", " );
			itoa( mtim_get_int( recv, 1 ), &output[strlen(output)], 10 );
			strcat( output, ", " );
			itoa( mtim_get_int( recv, 2 ), &output[strlen(output)], 10 );
			strcat( output, "\n" );
			uart_write( uport, output, strlen(output) );
		}else{
			mti_send( uport, errm );
		}
	}
	sleep_ms( &tmr, 1000 );

}
